let lazyImageObserver = null
const imgElMap = new Map()

export default {
    mounted(el, binding) {
        // 添加观察
        lazyload(el)

        // 将图片地址存储到Map中
        imgElMap.set(el, binding.value)
    },
    unmounted(el) {
        clear(el)
    }
}

// map,observer清理
function clear(el) {
    // 移除观察
    lazyImageObserver?.unobserve(el)

    // 删除Map属性
    imgElMap.delete(el)
}

// 懒加载函数  
function lazyload(el) {
    if ('IntersectionObserver' in window) {
        if (!lazyImageObserver) {
            lazyImageObserver = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    if (entry.isIntersecting) {
                        const { target } = entry;
                        target.src = imgElMap.get(target);
                        clear(target)
                    }
                });
            });
        }

        lazyImageObserver.observe(el);
    } else {
        // 浏览器不支持IntersectionObserver时，可以使用以下方式节流
        let flag = false
        function checkLazyImages() {
            if (!flag) {
                flag = true
                setTimeout(() => {
                    flag = false
                    imgElMap.forEach(function (value, key) {
                        if (key.offsetTop < window.innerHeight + window.scrollY) {
                            key.src = value;
                            clear(key)
                        }
                    });
                }, 500)
            }
        }

        window.onscroll = checkLazyImages
        window.onresize = checkLazyImages
        window.onload = checkLazyImages
    }
}